package com.yuoj.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.dfa.FoundWord;
import cn.hutool.dfa.WordTree;
import com.yuoj.codesandbox.model.dto.ExecuteCodeRequest;
import com.yuoj.codesandbox.model.dto.ExecuteCodeResponse;
import com.yuoj.codesandbox.model.enums.JudgeInfo;
import com.yuoj.codesandbox.utils.ProcessUtils;
import com.yuoj.codesandbox.model.ProcessExecuteMessage;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class JavaNativeCodeSandboxOld implements CodeSandbox {

    private static final String GLOBAL_CODE_DIR_NAME = "tmpCode";

    private static final String GLOBAL_JAVA_CLASS_NAME = "SleepError.java";

    private static final List<String> blackList = Arrays.asList("Files", "exec");

    private static final WordTree wordTree;

    static {
        //校验代码
        wordTree = new WordTree();
        wordTree.addWords(blackList);

    }


    private static final long TIME_OUT = 5000L;

    public static void main(String[] args) {
        JavaNativeCodeSandboxOld javaNativeCodeSandboxOld = new JavaNativeCodeSandboxOld();
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        String code = ResourceUtil.readStr("testCode/simpleComputer/Main.java", StandardCharsets.UTF_8);
//        String code = ResourceUtil.readStr("testCode/unsafeCode/SleepError.java", StandardCharsets.UTF_8);
        executeCodeRequest.setCode(code);
        executeCodeRequest.setLanguage("java");
        ExecuteCodeResponse executeCodeResponse = javaNativeCodeSandboxOld.executeCode(executeCodeRequest);
    }


    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest excuteCodeRequest) {
        List<String> inputList = excuteCodeRequest.getInputList();
        String code = excuteCodeRequest.getCode();
        String language = excuteCodeRequest.getLanguage();
        FoundWord foundWord = wordTree.matchWord(code);

        if (foundWord != null) {
            System.out.println("敏感词：" + foundWord.getWord());
            return null;
        }

        String userDir = System.getProperty("user.dir");
        String globalCodePathName = userDir + File.separator + GLOBAL_CODE_DIR_NAME;
        //判断全局代码目录是否存在，没有则创建
        if (!FileUtil.exist(globalCodePathName)) {
            FileUtil.mkdir(globalCodePathName);
        }
        //把用户的的代码隔离存放
        String userCodeParentPath = globalCodePathName + File.separator + UUID.randomUUID();
        String userCodePath = userCodeParentPath + File.separator + GLOBAL_JAVA_CLASS_NAME;
        File userCodeFile = FileUtil.writeString(code, userCodePath, StandardCharsets.UTF_8);
        List<ProcessExecuteMessage> processExecuteMessageList = new ArrayList<>();
        String compileCmd = String.format("javac -encoding utf-8 %s", userCodeFile.getAbsoluteFile());
        try {
            Process compileProcess = Runtime.getRuntime().exec(compileCmd);
            ProcessExecuteMessage processExecuteMessage = ProcessUtils.runProcessAndGetMessage(compileProcess, "编译");
            System.out.println(processExecuteMessage);
            processExecuteMessageList.add(processExecuteMessage);
        } catch (Exception e) {
            return getResponse(e);
        }
        //执行代码，获取输出结果
        for (String input : inputList) {
            String runCmd = String.format("java -Xmx256m -Dfile.encoding=UTF-8  -cp %s Main %s", userCodeParentPath, input);
            try {
                Process runProcess = Runtime.getRuntime().exec(runCmd);
                //超时控制
                new Thread(() -> {
                    try {
                        Thread.sleep(TIME_OUT);
                        runProcess.destroy();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
                ProcessExecuteMessage processExecuteMessage = ProcessUtils.runProcessAndGetMessage(runProcess, "运行");
                System.out.println(processExecuteMessage);
            } catch (Exception e) {
                return getResponse(e);
            }
        }
        //收集整理输出结果
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        List<String> outPutList = new ArrayList<>();
        Long maxTime = 0L;
        for (ProcessExecuteMessage processExecuteMessage : processExecuteMessageList) {
            String errorMessage = processExecuteMessage.getErrorMessage();
            if (StrUtil.isNotBlank(errorMessage)) {
                executeCodeResponse.setMessage(errorMessage);
                executeCodeResponse.setStatus(3);
                break;
            }
            if (processExecuteMessage.getTime() != null) {
                Long time = processExecuteMessage.getTime();
                maxTime = Math.max(maxTime, time);
            }
            outPutList.add(processExecuteMessage.getMessage());
        }
        if (outPutList.size() == processExecuteMessageList.size()) {
            executeCodeResponse.setStatus(1);
        }
        executeCodeResponse.setOutPutList(outPutList);
        JudgeInfo judgeInfo = new JudgeInfo();
        judgeInfo.setMemory(200L);
        judgeInfo.setLimit(maxTime);
        executeCodeResponse.setJudgeInfo(judgeInfo);
        //w文件清理
//        if (userCodeFile.getParentFile() != null) {
//            boolean del = FileUtil.del(userCodeParentPath);
//            System.out.println("删除:" + (del ? "成功" : "失败"));
//        }

        return executeCodeResponse;
    }

    private ExecuteCodeResponse getResponse(Throwable e) {
        ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
        executeCodeResponse.setOutPutList(new ArrayList<>());
        executeCodeResponse.setMessage(e.getMessage());
        executeCodeResponse.setStatus(2);
        executeCodeResponse.setJudgeInfo(new JudgeInfo());
        return executeCodeResponse;
    }
}
